﻿using DevilTools.Commons;
using Microsoft.Win32;

namespace DevilTools.Envs;

/// <summary>
/// 设置环境变量命令行工具
/// </summary>
///
/// <remarks>
/// 用法:
/// <br />
/// $> envs --name VAR_NAME --value "VAR_VALUE" [--machine]
/// </remarks>
public class Program {
    public static void Main(string[] args) {
        var parser = new CommandLineParser()
            .RequireOption("name")
            .RequireOption("value")
            .CheckIsBool("machine");

        try {
            parser.Parse(args);
            // parser.Parse(["--name", "S_VAR", "--value", "%TEST_VAR%\\xxcvcxv", "--machine"]);
            parser.Validate();

            var name = parser.GetOptionValue("name");
            var value = parser.GetOptionValue("value");
            value = value.Replace("\\%", "%");

            var hasVariable = value.Contains('%');
            var valueKind = hasVariable ? RegistryValueKind.ExpandString : RegistryValueKind.String;

            var isMachine = parser.GetBool("machine");
            var keyName = isMachine
                ? @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
                : @"HKEY_CURRENT_USER\Environment";

            Registry.SetValue(keyName, name, value, valueKind);
            Console.WriteLine("1");
        } catch (CommandLineParser.ValidationException e) {
            Console.WriteLine($"0,{e.Errors.FirstOrDefault()}");
        } catch (UnauthorizedAccessException e) {
            Console.WriteLine($"0,{e.Message}");
        } catch (Exception e) {
            Console.WriteLine($"0,{e.Message}");
        }
    }
}
